<script setup>
import { ref, defineEmits, watch,computed } from 'vue'
import { useStore } from 'vuex'
import { fetchEventSource } from '@microsoft/fetch-event-source'
import { v4 as uuidv4 } from 'uuid';
import axios from 'axios'
const store = useStore()
const sessionList = ref(store.state.sessionMsg||[])
const sayType = computed(() => store.state.sayType);
const sendIndex = ref(0)
const textarea = ref('')
const loading = ref('')
const emit = defineEmits(['sendmsg'])
const controllers =ref('')
const status =ref(true)
// const tokens = 'Bearer sk-c601e9cf14934946b264c4b1de7c8f93'
const tokens = 'Bearer pat_yx09Tf23WblDgXsQTc3e8sfGl84k0gRsfnTmSmRhlWPszIvA2gTrau3Bf3YuCdoj'
// 监听当前会话
watch(
    () => store.state.sessionMsg,
    (newPath, oldPath) => {
        sessionList.value = newPath
    },
    {
        deep: true
    }
)
// 刷新
const refresh = () => {
    loading.value = 'loading'
    setTimeout(() => {
        loading.value = ''
    }, 500)
}
var timer = null
// 发送消息
const send =  () => {
    if(!status.value){
        return
    }
    if (textarea.value) {
        // 每次发送清除定时器
        if (timer) {
            clearTimeout(timer)
        }
        sendIndex.value=0
        const content = textarea.value
        // sayType   1:普通会话  2：图片会话
        if(sayType.value==1){
            sessionList.value.push({
                content:content,
                request_id: uuidv4(),
                role:"user",
                type:"me"
            })
        }else{
             sessionList.value.push({
                content:content,
                request_id: uuidv4(),
                role:"user",
                type:"me"
            })
        }
        store.commit('setSessionMsg', sessionList.value)
        if(sayType.value==1){
                sseSendStream(content)
        }else{
            sendImg(content)
        }
        textarea.value = ''
    }
}
// 普通会话
var abortController = null
const sseSendStream =  (content) => {
    store.commit('setLoading', true)
    if(abortController){
        abortController = null
      }
    abortController = new AbortController()
    // let url = 'https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation'
    let url = 'https://api.coze.cn/v3/chat'
    // 模型参数
    // let params = {
    //     model: 'qwen-max',
    //     input: {
    //         messages: [
    //             {
    //                 role: 'user',
    //                 content: content,
    //             },
    //         ]
    //     },
    //     parameters: {}
    // }
     // 模型参数
    let params = {
        "bot_id": "7405395880901427212",
        "user_id": uuidv4(),
        "stream": true,
        "auto_save_history":true,
        "additional_messages":[
            {
                "role":"user",
                "content":content,
                "content_type":"text"
            }
        ]
    }
       fetchEventSource(url, {
                method: 'post',
                headers: {
                    'Content-Type': 'application/json',
                    // 'X-DashScope-SSE': 'enable',
                    Accept:"text/event-stream",
                    Authorization: tokens
                },
                // responseType: 'text/event-stream',
                body: JSON.stringify(params),
                openWhenHidden: true,
                signal:abortController.signal,
                async onopen(response) {
                    //建立连接的回调
                    status.value=false
                    store.commit('setStatus', false)
                    console.log('建立连接的回调', response)
                    sessionList.value.push({
                        type:"loading",
                    })
                },
                onmessage(msg) {
                    console.log(msg)
                    //接收一次数据段时回调，因为是流式返回，所以这个回调会被调用多次
                    if (msg.event == 'conversation.message.delta') {
                        //进行连接正常的操作
                        try {
                            const dataObj = JSON.parse(msg.data)
                            // const strings = dataObj.output.text.split('')
                            if (sendIndex.value == 0) {
                                sessionList.value[sessionList.value.length - 1]=dataObj
                            }else{
                                sessionList.value[sessionList.value.length - 1].content += dataObj.content
                            }
                            store.commit('setSessionMsg', sessionList.value)
                            sendIndex.value=2
                            // setTimeout(() => {
                            //     simulateGPTResponse(strings)
                            // }, 1000)
                        } catch (e) {}
                    }
                },
                onclose() {
                    console.log("停止了")
                    status.value=true
                    store.commit('setStatus', true)
                    //正常结束的回调
                    //在这里写一些GPT回答结束后的一些操作
                },
                onerror(err) {
                    //连接出现异常回调
                    // 取消请求
                    throw err
                }
            })
}
// 图片会话
function sendImg(content,again){
    let url = "https://dashscope.aliyuncs.com/api/v1/services/aigc/text2image/image-synthesis"
    let params = {
        model: 'wanx-v1',
        input: {
            prompt:content,
        },
        parameters: {
            "style": "<sketch>",
            "size": "1024*1024",
            "n":4,
            "seed":42,
            "strength": 0.5,
            "ref_mode": "repaint"
        }
    }
    axios({
        url: url,
        method: 'post',
        headers:{
            'Content-Type': 'application/json',
            "X-DashScope-Async":"enable",
            Authorization: tokens,
        },
        data:params,
    }).then(res=>{
        if(!again){
            sessionList.value.push({
                type:"loading",
                text:"正在生成中"
            })
            store.commit('setSessionMsg', sessionList.value)
        }
        getImg(res.data.output)
    })
}
//获取图片
function getImg(params){
    axios({
        url:`https://dashscope.aliyuncs.com/api/v1/tasks/${params.task_id}`,
        method: 'get',
        headers:{
            'Content-Type': 'application/json',
            Authorization: tokens,
            type:"send"
        },
    }).then(res=>{
        if(res.data.output.task_status=="PENDING"||res.data.output.task_status=="RUNNING"){
            setTimeout(()=>{
                getImg(params,"again")
            },2000)
        }
        if(res.data.output.task_status=="SUCCEEDED"){
            sessionList.value[sessionList.value.length-1]=res.data
            store.commit('setSessionMsg', sessionList.value)
        }
    })
}
function simulateGPTResponse(strings) {
    if (timer) {
        clearTimeout(timer)
    }
    if (sendIndex.value < strings.length) {
        const char = strings[sendIndex.value++]
        sessionList.value[sessionList.value.length - 1].output.text += char
        store.commit('setSessionMsg', sessionList.value)
        timer = setTimeout(() => {
            simulateGPTResponse(strings)
        }, 50)
    }
}
const beforeUpload = (e) => {
    console.log(e)
}
function stop(){
    abortController.abort();
    status.value=true
    store.commit('setStatus', true)
}
</script>
<template>
    <div class="footer">
        <div class="sendmsg">
            <div class="left">
                <img
                    src="../assets/img/icon.png"
                    alt=""
                    height="20px"
                    :class="loading"
                    @click="refresh"
                />
                <div>
                    <el-upload
                        ref="uploadRef"
                        class="upload-demo"
                        action=""
                        :before-upload="beforeUpload"
                    >
                        <template #trigger>
                            <img src="../assets/img/upimg.svg" alt="" height="20px" />
                        </template>
                    </el-upload>
                </div>
                <div>
                    <el-upload
                        ref="uploadRef"
                        class="upload-demo"
                        action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15"
                        :auto-upload="false"
                    >
                        <template #trigger>
                            <img src="../assets/img/file.svg" alt="" height="20px" />
                        </template>
                    </el-upload>
                </div>
            </div>
            <div class="send" @click="status?send():stop()">
                <img :src="status?'../assets/img/send.svg':'../assets/img/stop.svg'" alt="" height="16px" />
            </div>
        </div>
        <el-input
            v-model="textarea"
            @keyup.enter="send"
            :rows="5"
            type="textarea"
            placeholder="在这里输入你的问题"
        />
    </div>
</template>

<style lang="stylus" scoped>
.footer
    height: 100%
    .sendmsg
        height: 40px
        display: flex
        justify-content: space-between
        align-items: center
        img
            cursor pointer
        .left
            display: flex
            align-items: center
            >div
                width: 30px
                height: 30px
                display: flex
                align-items: center
                justify-content: center
                margin-left: 10px
                border-radius: 8px
                &:hover{
                    background: #e9ebf1
                }
                .upload-demo
                    width: 100%;
                    height: 100%;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    .el-upload-list
                        display: none
        .send
            width 35px
            height: 30px
            display: flex
            border-radius: 6px
            background: #1976d2
            align-items: center
            justify-content: center
    :deep(.el-textarea__inner)
        box-shadow: none
        padding: 0
        color: #000

    .loading {
        width: 20px;
        height: 20px;
        border: 2px solid #1976d2;
        border-bottom-color: transparent;
        border-radius: 50%;
        display: inline-block;
        box-sizing: border-box;
        animation: loadingrotation 0.4s linear infinite;
    }

    @keyframes loadingrotation {
        0% {
            transform: rotate(0deg);
        }
        100% {
            transform: rotate(360deg);
        }
    }
</style>
